/*
 * Copyright (c) 2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * TodoStore
 */

const AppDispatcher = require('../dispatcher/AppDispatcher');
const TodoConstants = require('../constants/TodoConstants');
const EventEmitter = require('events').EventEmitter;
const assign = require('object-assign');

const CHANGE_EVENT = 'change';
// var textList = [
//   {id: 0, text: '111', checked: true},
//   {id: 1, text: '222', checked: false}
// ];
var textList = [];


const TodoStore = assign({}, EventEmitter.prototype, {
  _create(text) {
    let json = {};

    if (textList.length == 0){
      json.id = 0;
    } else {
      json.id = textList[textList.length-1].id + 1;
    }
    json.text = text;
    json.checked = false;
    textList.push(json);
  },

  _delete(index) {

    for (let i = 0; i < textList.length; i++) {

      if (textList[i].id == index) {

        textList.splice(i, 1);
        break;
      }
    }
  },

  _editor(index, text) {

    for (let i = 0; i < textList.length; i++) {

      if (textList[i].id == index) {

        let json = {};
        json.id = i;
        json.text = text;
        json.checked = textList[i].checked;
        textList.splice(i, 1, json);
        break;
      }
    }
  },

  _stateChange(index) {
    for (let i=0; i< textList.length; i++) {

      if (textList[i].id == index) {

        textList[i].checked = !textList[i].checked;
        break;
      }
    }
  },

  _getAll() {
    let undoList = [];
    let doneList = [];

    for (let i=0; i< textList.length; i++) {

      if (textList[i].checked) {
        doneList.push(textList[i]);
      } else {
        undoList.push(textList[i]);
      }
    }
    return [undoList, doneList];
  },

  _emitChange() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
});


// Register callback to handle all updates
AppDispatcher.register(function(payload) {

	switch (payload.actionType) {
    case TodoConstants.CREATE:
      TodoStore._create(payload.text);
      TodoStore._emitChange();
      break;

    case TodoConstants.DELETE:
      TodoStore._delete(payload.index);
      TodoStore._emitChange();
      break;

    case TodoConstants.EDITOR:
      TodoStore._editor(payload.index, payload.text);
      TodoStore._emitChange();
      break;

    case TodoConstants.STATE:
      TodoStore._stateChange(payload.index);
      TodoStore._emitChange();
      break;

      default:
  }
  return true;
});

module.exports = TodoStore;